/**
 * 
 */
package org.mspring.mlog.web.security.login;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

/**
 * @author Gao Youbo
 * @since 2013-6-8
 * @description
 * @TODO
 */
public class UrlMappingLoginPageStrategy implements LoginPageStrategy {

    private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    private boolean useForward = false;

    public boolean isUseForward() {
        return useForward;
    }

    public void setUseForward(boolean useForward) {
        this.useForward = useForward;
    }

    /**
     * 在这里判断如何跳转登录页
     */
    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // TODO Auto-generated method stub
        String redirectUrl = getRedirectUrl(request, response);
        if (useForward) {
            RequestDispatcher dispatcher = request.getRequestDispatcher(redirectUrl);
            dispatcher.forward(request, response);
            return;
        } else {
            redirectStrategy.sendRedirect(request, response, redirectUrl);
        }
    }

    /**
     * 获取跳转地址
     * 
     * @param request
     * @param response
     * @return
     */
    protected String getRedirectUrl(HttpServletRequest request, HttpServletResponse response) {
        RequestMatcher adminUrlMatcher = new AntPathRequestMatcher("/admin/**");
        // UCenter后台
        RequestMatcher userUrlMatcher = new AntPathRequestMatcher("/u/*/admin/**");

        String redirectUrl = "";
        if (adminUrlMatcher.matches(request) && !userUrlMatcher.matches(request)) {
            redirectUrl = request.getContextPath() + "/admin/login";
        } else {
            redirectUrl = request.getContextPath() + "/login";
        }
        return redirectUrl;
    }

}
